#!/usr/bin/env python
# -*- coding: utf-8 -*-
# 时间     : 2021-08-26 17:03
# 作者     : DL (584054432@qq.com)
# 网址     : https://gitee.com/dingliangPython/
# 软件版本 : Python3.7.3
# 功能     ：

import datetime
import logging
import sys
import traceback
from ctypes import windll

import win32con


def show_message(msg, title = '警告'):
    result = windll.user32.MessageBoxA(0, msg.encode('gbk'), title.encode('gbk'), 1 | win32con.MB_ICONWARNING)
    return True if result == 1 else False


## @detail 创建记录异常的信息
class ExceptHookHandler(object):
    ## @detail 构造函数
    #  @param logFile: log的输入地址
    #  @param mainFrame: 是否需要在主窗口中弹出提醒
    def __init__(self, logFile = None, mainFrame = None):
        self.__LogFile = logFile if logFile else './error.log'
        self.__MainFrame = mainFrame

        self.__Logger = self.__BuildLogger()
        # 重定向异常捕获
        sys.excepthook = self.__HandleException

    ## @detail 创建logger类
    def __BuildLogger(self):
        logger = logging.getLogger("main.error")
        logger.setLevel(logging.DEBUG)
        logger.addHandler(logging.FileHandler(self.__LogFile))
        return logger

    ## @detail 捕获及输出异常类
    #  @param excType: 异常类型
    #  @param excValue: 异常对象
    #  @param tb: 异常的trace back
    def __HandleException(self, excType, excValue, tb):
        # first logger
        try:
            currentTime = datetime.datetime.now()
            self.__Logger.info(' * {} {}\n'.format(currentTime.strftime("%Y-%m-%d %H:%M:%S"), "-" * 60))
            self.__Logger.error("异常信息：", exc_info = (excType, excValue, tb))
            self.__Logger.info('\n * {} {}\n'.format(currentTime.strftime("%Y-%m-%d %H:%M:%S"), "-" * 60))
        except:
            pass

        # 调用默认处理程序
        sys.__excepthook__(excType, excValue, tb)

        err_msg = ''.join(traceback.format_exception(excType, excValue, tb))
        err_msg += '\n 应用程序发生错误，请联系管理人员。。。'
        # 显示异常
        if self.__MainFrame:
            show_message(err_msg)